package com.example.qimo

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.example.qimo.weather.CityInfo
import com.example.qimo.weather.Data
import com.example.qimo.weather.Forecast
import com.example.qimo.weather.weather
import java.io.StringReader
import androidx.localbroadcastmanager.content.LocalBroadcastManager

class Main2Activity : AppCompatActivity() {
    val baseURL = "http://t.weather.itboy.net/api/weather/city/"
    private lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)

        val cityCode: String? = intent.getStringExtra("city_code")
        if (cityCode == null) {
            Log.e("Main2Activity", "City code is null")
            return
        }

        val queue: RequestQueue = Volley.newRequestQueue(this)
        val stringRequest = StringRequest(
            Request.Method.GET,
            baseURL + cityCode,
            { response ->
                Log.d("Main2Activity", "Server Response: $response")
                val gson = Gson()
                val weatherType = object : TypeToken<weather>() {}.type
                val reader = StringReader(response)
                val weather: weather = gson.fromJson(reader, weatherType)

                val textView_city = findViewById<TextView>(R.id.textView_city)
                textView_city.text = weather.cityInfo.city

                val textView_province = findViewById<TextView>(R.id.textView_province)
                textView_province.text = weather.cityInfo.parent

                val textView_shidu = findViewById<TextView>(R.id.textView_shidu)
                textView_shidu.text = weather.data.shidu

                val textView_wendu = findViewById<TextView>(R.id.textView_wendu)
                textView_wendu.text = weather.data.wendu

                val firstDay: Forecast = weather.data.forecast.firstOrNull() ?: Forecast(
                    aqi = "50",
                    date = "2024-11-14",
                    fl = "10℃",
                    fx = "北风",
                    high = "20℃",
                    low = "10℃",
                    notice = "注意保暖",
                    sunrise = "06:30",
                    sunset = "18:00",
                    type = "晴",
                    week = "星期四",
                    ymd = "2024-11-14"
                )

                val imageView = findViewById<ImageView>(R.id.imageView)
                when (firstDay.type) {
                    "晴" -> imageView.setImageResource(R.drawable.sun)
                    "阴" -> imageView.setImageResource(R.drawable.cloud)
                    "多云" -> imageView.setImageResource(R.drawable.mcloud)
                    "阵雨" -> imageView.setImageResource(R.drawable.rain)
                    else -> imageView.setImageResource(R.drawable.thunder)
                }

                val listView = findViewById<ListView>(R.id.listView)
                val adapter = ArrayAdapter<Forecast>(this, android.R.layout.simple_list_item_1, weather.data.forecast)
                listView.adapter = adapter

                Log.d("Main2Activity", "${weather.cityInfo.city} ${weather.cityInfo.parent}")

                sharedPreferences = getSharedPreferences("AppPrefs", Context.MODE_PRIVATE)

                val buttonFavorite = findViewById<Button>(R.id.button_favorite)
                buttonFavorite.setOnClickListener {
                    val city = weather.cityInfo.city
                    val cityKey = weather.cityInfo.citykey
                    saveFavoriteCity(city, cityKey)

                    // 发送本地广播
                    val intent = Intent("REFRESH_FAVORITE_CITIES")
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
                }
            },
            { error ->
                Log.e("Main2Activity", "Error: ${error.message}")
            }
        )
        queue.add(stringRequest)
    }

    private fun saveFavoriteCity(city: String, cityKey: String) {
        val editor = sharedPreferences.edit()
        val favoriteCities = getFavoriteCities()

        if (!favoriteCities.containsKey(cityKey)) {
            favoriteCities[cityKey] = city
            editor.putString("favorite_cities", Gson().toJson(favoriteCities))
            editor.apply()
            Log.d("Main2Activity", "City $city ($cityKey) added to favorites")
        } else {
            Log.d("Main2Activity", "City $city ($cityKey) is already in favorites")
        }
    }

    private fun getFavoriteCities(): MutableMap<String, String> {
        val jsonString = sharedPreferences.getString("favorite_cities", "{}")
        val gson = Gson()
        val type = object : TypeToken<Map<String, String>>() {}.type
        return gson.fromJson<Map<String, String>>(jsonString, type).toMutableMap()
    }
}